<template>
  <div class="attendance-container">
    <a-card title="考勤管理">
      <template #extra>
        <a-range-picker
            v-model:value="dateRange"
            @change="handleDateChange"
            style="width: 250px; margin-right: 10px"
        />
        <a-button type="primary" @click="exportData">导出考勤</a-button>
      </template>

      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane key="1" tab="考勤记录">
          <a-table
              :columns="columns"
              :data-source="attendanceData"
              :pagination="pagination"
              row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-button size="small" @click="editAttendance(record)">编辑</a-button>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="考勤统计">
          <div class="statistics-container">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-card title="正常出勤" :bordered="false">
                  <div class="stat-card">
                    <h2>85%</h2>
                    <p>较上月 <span class="increase">↑2%</span></p>
                  </div>
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card title="迟到人数" :bordered="false">
                  <div class="stat-card">
                    <h2>12</h2>
                    <p>较上月 <span class="decrease">↓3</span></p>
                  </div>
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card title="缺勤人数" :bordered="false">
                  <div class="stat-card">
                    <h2>5</h2>
                    <p>较上月 <span class="increase">↑1</span></p>
                  </div>
                </a-card>
              </a-col>
            </a-row>

            <a-card title="月度考勤趋势" style="margin-top: 16px;">
              <div id="attendance-trend-chart" style="height: 300px;"></div>
            </a-card>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

const activeTab = ref('1')
const dateRange = ref([dayjs().startOf('month'), dayjs().endOf('month')])

// 考勤表格列配置
const columns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date'
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '工号',
    dataIndex: 'employeeId',
    key: 'employeeId'
  },
  {
    title: '上班时间',
    dataIndex: 'checkIn',
    key: 'checkIn'
  },
  {
    title: '下班时间',
    dataIndex: 'checkOut',
    key: 'checkOut'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '操作',
    key: 'action',
    width: '100px'
  }
]

// 考勤数据
const attendanceData = ref([
  { id: 1, date: '2023-10-01', name: '张三', employeeId: '1001', checkIn: '08:30', checkOut: '18:00', status: 1 },
  { id: 2, date: '2023-10-01', name: '李四', employeeId: '1002', checkIn: '09:15', checkOut: '18:30', status: 2 },
  { id: 3, date: '2023-10-01', name: '王五', employeeId: '1003', checkIn: '08:45', checkOut: '17:45', status: 1 },
  { id: 4, date: '2023-10-02', name: '张三', employeeId: '1001', checkIn: '08:35', checkOut: '18:10', status: 1 },
  { id: 5, date: '2023-10-02', name: '李四', employeeId: '1002', checkIn: '08:50', checkOut: '18:20', status: 1 },
  { id: 6, date: '2023-10-02', name: '王五', employeeId: '1003', checkIn: '', checkOut: '', status: 3 }
])

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 6
})

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '正常',
    2: '迟到',
    3: '缺勤',
    4: '早退',
    5: '请假'
  }
  return statusMap[status] || '未知'
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    1: 'green',
    2: 'orange',
    3: 'red',
    4: 'gold',
    5: 'blue'
  }
  return colorMap[status] || 'default'
}

// 编辑考勤记录
const editAttendance = (record) => {
  console.log('编辑考勤记录:', record)
}

// 导出数据
const exportData = () => {
  console.log('导出考勤数据')
}

// 日期范围变化
const handleDateChange = (dates) => {
  console.log('日期范围变化:', dates)
  // 实际项目中应该根据日期范围重新获取数据
}

let myChart = null // 存储图表实例

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('attendance-trend-chart')

  // 确保DOM元素存在
  if (!chartDom) {
    return
  }

  // 如果已有图表实例，先销毁
  if (myChart) {
    myChart.dispose()
  }

  myChart = echarts.init(chartDom)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(item => {
          result += `${item.marker} ${item.seriesName}: ${item.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['正常出勤', '迟到', '缺勤'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月'],
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '正常出勤',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 154],
        smooth: true,
        lineStyle: {
          width: 3
        },
        symbolSize: 8,
        itemStyle: {
          color: '#52c41a'
        }
      },
      {
        name: '迟到',
        type: 'line',
        data: [20, 18, 19, 23, 29, 33, 31, 25, 22, 18],
        smooth: true,
        lineStyle: {
          width: 3
        },
        symbolSize: 8,
        itemStyle: {
          color: '#faad14'
        }
      },
      {
        name: '缺勤',
        type: 'line',
        data: [5, 7, 3, 8, 12, 9, 6, 5, 4, 3],
        smooth: true,
        lineStyle: {
          width: 3
        },
        symbolSize: 8,
        itemStyle: {
          color: '#f5222d'
        }
      }
    ]
  }

  myChart.setOption(option)

  window.addEventListener('resize', handleResize)
}

// 处理窗口resize
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 标签切换处理
const handleTabChange = (activeKey) => {
  // 当切换到"考勤统计"标签时初始化图表
  if (activeKey === '2') {
    // 使用nextTick确保DOM更新完成
    nextTick(() => {
      initChart()
    })
  }
}

// 组件卸载时清理
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  window.removeEventListener('resize', handleResize)
})

onMounted(() => {
  // 如果默认是"考勤统计"标签，初始化图表
  if (activeTab.value === '2') {
    nextTick(() => {
      initChart()
    })
  }
})
</script>

<style scoped>
.attendance-container {
  padding: 20px;
}

.stat-card {
  text-align: center;
}

.stat-card h2 {
  font-size: 24px;
  margin-bottom: 8px;
}

.stat-card p {
  margin: 0;
  color: #999;
}

.increase {
  color: #52c41a;
}

.decrease {
  color: #f5222d;
}

.statistics-container {
  margin-top: 16px;
}
</style>